//
//  TodayDetailCalendarController.swift
//  MoyoungHome
//
//  Created by 易先生 on 2022/9/21.
//

import UIKit
import MYModule
import RxDataSources
import Differentiator
import NSObject_Rx
import RxCocoa

class CalendarController: ViewController {

	public var showType: CalendarShowType = .heart24h
    
	public let reloadRelay = PublishRelay<Date>()
    
    public var revealAll: Bool = true

	override func viewDidLoad() {
		super.viewDidLoad()
        
        setNavigationBar()
        
		viewModel.getCalendarDatas()
        
        collectionView.reloadData()
        
	}

	override func makeUI() {
		super.makeUI()
        
        weekCalendarView.backgroundColor = UIColor.background
        
		view.addSubview(weekCalendarView)
		view.addSubview(collectionView)

		weekCalendarView.snp.makeConstraints { make in
            make.top.equalTo(navigation.bar.snp.bottom)
			make.leading.trailing.equalToSuperview()
			make.height.equalTo(30)
		}

		collectionView.snp.makeConstraints { make in
            make.top.equalTo(weekCalendarView.snp.bottom)
			make.bottom.leading.trailing.equalToSuperview()
		}
	}

	private func setNavigationBar() {
        self.navigation.item.title = "\(Date().year)"
        
        navigation.bar.titleTextAttributes = [.foregroundColor: UIColor.assist_222222]
        navigation.bar.tintColor = UIColor.assist_222222
        navigation.bar.barTintColor = UIColor.background
        
    }

	
	private lazy var viewModel: CalendarViewModel = {
		let viewModel = CalendarViewModel(showType: showType)
		return viewModel
	}()

	private lazy var weekCalendarView: CalendarWeekView = {
		let weekCalendarView = CalendarWeekView()
		weekCalendarView.updateDatas(datas: ["unit_week_full_1".language, "unit_week_full_2".language, "unit_week_full_3".language, "unit_week_full_4".language, "unit_week_full_5".language, "unit_week_full_6".language, "unit_week_full_7".language], textColor: viewModel.getWeekCalendarTextColor())
		return weekCalendarView
	}()

	private lazy var collectionView: UICollectionView = {
		let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayoutView)
		collectionView.delegate = self
		collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.background
		collectionView.register(CalendarTableCell.self, forCellWithReuseIdentifier: CalendarTableCell.reuseIdentifier)
        collectionView.register(CalendarActivityTableCell.self, forCellWithReuseIdentifier: CalendarActivityTableCell.reuseIdentifier)
        
		collectionView.register(CalendarHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "TodayDetailCalendarHeadView")
		return collectionView
	}()

	private lazy var flowLayoutView: UICollectionViewFlowLayout = {
		let flowLayoutView = UICollectionViewFlowLayout()
		let itemWidth = (view.bounds.width - 70) / 7
		flowLayoutView.scrollDirection = .vertical
		flowLayoutView.itemSize = CGSize(width: itemWidth, height: 65)
		flowLayoutView.sectionInset = UIEdgeInsets(top: 20.0, left: 17.5, bottom: 20.0, right: 17.5)
		flowLayoutView.minimumInteritemSpacing = 5.0
		flowLayoutView.minimumLineSpacing = 20.0
		flowLayoutView.headerReferenceSize = CGSize(width: view.bounds.width, height: 60)
		return flowLayoutView
	}()
}

extension CalendarController: UICollectionViewDataSource {

	func numberOfSections(in collectionView: UICollectionView) -> Int {
		return viewModel.numberOfSections()
	}

	func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
		return viewModel.numberOfItemsInSection(section: section)
	}

	func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
		let cellModel = viewModel.cellForItemAtCellModel(indexPath: indexPath)
        
        
        if self.showType == .step24h {
            
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CalendarActivityTableCell.reuseIdentifier, for: indexPath) as! CalendarActivityTableCell
            cell.bind(to: cellModel)
            
            return cell
            
        }
		let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CalendarTableCell.reuseIdentifier, for: indexPath) as! CalendarTableCell
		cell.bind(to: cellModel)
		return cell
	}

	func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

		if kind == UICollectionView.elementKindSectionHeader {
			
			let sectionView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "TodayDetailCalendarHeadView", for: indexPath) as! CalendarHeaderView
    
            let month = viewModel.calendarSections[indexPath.section].month
			sectionView.bind(to: month)
			return sectionView
		}
		return UICollectionReusableView()
	}

	func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
		let cellModel = viewModel.cellForItemAtCellModel(indexPath: indexPath)
		navigation.item.title = "\(cellModel.year)"
	}
}

extension CalendarController: UICollectionViewDelegate {

	func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
		let cellModel = viewModel.cellForItemAtCellModel(indexPath: indexPath)
		
        // 白板或者未到日期的天都不能看详情
        if cellModel.type == .past || cellModel.type == .future {
            return
        }
        
        // 显示点击
        
        viewModel.selectedItem?.isSelected = false
        cellModel.isSelected = true
        viewModel.selectedItem = cellModel
        collectionView.reloadData()
        
		let date = Date.init(year: cellModel.year,
			month: cellModel.month,
			day: cellModel.day,
			hour: 0,
			minute: 0)
        

        pushToDetailController(date: date)
	}
    
    
    func pushToDetailController(date: Date) {
        
        switch showType {
            
        case .step24h:
            
            let vc = ActivityHomeController()
            vc.showRightItem = false
            vc.revealAll = self.revealAll
            vc.viewModel = ActivityHomeViewModel()
            vc.provider = StepProvider(date: date)
            
            self.navigationController?.pushViewController(vc, animated: true)
            
        case .heart24h:
            
            let vc = HeartRateDetailController()
            vc.showRightItem = false
            vc.viewModel = HeartRateProvider(date: date)
            self.navigationController?.pushViewController(vc, animated: true)
            
        case .spo24h:
            
            let vc = BloodOxygenDetailController()
            vc.showRightItem = false
            vc.provider = BloodOxygenProvider(date: date)
            self.navigationController?.pushViewController(vc, animated: true)
            
        case .sleep24h:
            
            let vc = SleepViewController()
            vc.showRightItem = false
            vc.revealAll = self.revealAll
            let provider = SleepProvider(date: date)
            vc.provider = provider
            
            self.navigationController?.pushViewController(vc, animated: true)
            
        case .hrv24h:
            let vc = HRVDetailController()
            vc.showRightItem = false
            vc.viewModel = HRVProvider(date: date)
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        
    }

}
